﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;

namespace GradientSquares
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			this.InitializeComponent();

			this.Loaded += (sender, e) =>
			{
				// Insert code required on object creation below this point.
				using (FileStream fileStream = new FileStream(@"C:\Users\plottsc\Desktop\GradientSquares\Gradient.jpg", FileMode.Create))
				{
					JpegBitmapEncoder encoder = new JpegBitmapEncoder();
					encoder.Frames.Add(BitmapFrame.Create(CaptureScreen(this.gradientSquare, 96, 96)));
					encoder.QualityLevel = 100;
					encoder.Save(fileStream);
				}
			};
		}


		private static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY)
		{
			if (target == null)
			{
				return null;
			}
			Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
			RenderTargetBitmap rtb =
				new RenderTargetBitmap
				(
					(int)(bounds.Width * dpiX / 96.0),
					(int)(bounds.Height * dpiY / 96.0),
					dpiX,
					dpiY,
					PixelFormats.Pbgra32
				);
			DrawingVisual dv = new DrawingVisual();
			using (DrawingContext ctx = dv.RenderOpen())
			{
				VisualBrush vb = new VisualBrush(target);
				ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
			}
			rtb.Render(dv);
			return rtb;
		}
	}
}